<template>
    <div class="rightThematicMapFxff">
        <div class="title">
            <!-- {{typeName1}} -->
            防汛防风专题图
        </div>
        <div class="thematicMap">
            <div
                v-for="(item1, index1) in list"
                :class="{
                    thematicMapItem: true,
                    thematicMapItemActive: item1.state1,
                }"
                :key="index1 + 'child'"
                @click="handleItemClick($event, item1, index1)"
            >
                <div class="dataName">
                    <div class="dataImg">
                        <img :src="`./images/sjzx/icons/${item1.label}.png`" alt="">
                    </div>
                    <div class="dataWord">
                        {{ item1.label }}
                    </div>
                </div>
                <!-- <div class="contentLine">
                    <img src="/images/sjzx/trangle.png" alt="" />
                </div>-->
                <!-- <div class="num">{{ item1.count }}</div>  -->
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, toRefs, watch, onBeforeUnmount ,computed} from "vue";
import pointeManager from "../../../pointManager";
import { useStore } from "vuex";
import axios from "axios";
import doc from "../../../sjzxDoc";
import { ElNotification } from 'element-plus';
import Legend from './Legend.vue'
export default {
    components:{
        Legend
    },
    //props:["typeName"],
    setup() {
        let store = useStore();
        const userRegion = computed(()=>{return store.state.userRegion});
        watch(()=>{

        },()=>{})
        // 接口请求防汛防风列表 （九项）
        let themeList = reactive({ list: [] });
        // 获取数据
        const getFxffList = async (region) => {
            let sanFangurl = `${sjzxUrl}/api/tree/getRiskTree?ids=146`;
            if(region != undefined){
                sanFangurl = `${sjzxUrl}/api/tree/getRiskTree?ids=146&addvcd=${window.regionCode[region]}`;
            }
            const result = await axios.get(sanFangurl);
            const orderList = result.data;
            orderList.forEach((order) => {
                order.state1 = false;
            });
            themeList.list = orderList.slice(0, orderList.length - 1);
        };
        
        if (userRegion.value == "海南省") {
            getFxffList();
        } else {
            getFxffList(userRegion.value);
        }
        const { list } = toRefs(themeList);
        // 监听来自图例的变化
        watch(
            () => store.state.checkedCities,
            (newValue) => {
                list.value.forEach((item1, index1) => {
                    item1.state1 = false;
                        if (newValue.indexOf(item1.label)>-1) {
                            item1.state1 = true;
                        }
                });
            }
        );
        const removeInfoBox = ()=>{
            const oneDiv  = window.document.getElementById("infoBox2");
            oneDiv.style.display = "none";
            const oneDiv1 = window.document.getElementById("infoBox4");
            oneDiv1.style.display = "none";
            const oneDiv2 = window.document.getElementById("infoBox1");
            oneDiv2.style.display = "none";
        }
        //球上点位拾取
        let currentEntity = null;
        const pointHandleClick = (entity) => {
            console.log(entity)
            // if (currentEntity) {
            //     currentEntity._billboard._image._value =`./images/sjzx/icons/${entity.type}.png`
            // }
            // entity._billboard._image._value =`./images/sjzx/icons/${entity.type}1.png`;
            let parma = null;
            if (entity.type == "渔船") {
                parma = "condition";
            } else {
                parma = "id";
            }
            var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(entity.position._value); //笛卡尔转84
            var lat=Cesium.Math.toDegrees(cartographicPosition.latitude);
            var lng=Cesium.Math.toDegrees(cartographicPosition.longitude);
            let option = {
                destination: Cesium.Cartesian3.fromDegrees(
                    parseFloat(lng), 
                    parseFloat(lat),
                    80000
                ),
                duration:1.5
            }
            viewer.camera.flyTo(option);
            removeInfoBox()
            option.complete = ()=>{
                axios
                .get(
                    `${sjzxUrl}${entity.kbApiDetail}?${parma}=${entity.detailId}`
                )
                .then((res) => {
                    console.log(res)
                    if (entity.type == "渔船") {
                        //查看渔船
                        let vData = res.data.data;
                        store.commit("changeYCList", vData);
                        
                        addBoundInfoBox(entity.position._value, "infoBox2");
                        currentEntity = entity
                        //需要加全景
                    } else if (entity.type == "地质灾害隐患点") {
                        let vData = res.data.data;
                        let obj = {
                            "隐患基本情况":{},
                            "市县落实情况":{},
                            "省级行业主管部门核查情况":{}
                        };
                        let dic = doc[entity.type];
                        // 原顺序
                        for (let key in dic) {
                            if(vData.baseInfo.hasOwnProperty(key)){
                                obj["隐患基本情况"][dic[key]] = vData.baseInfo[key];
                            }
                            if(vData.check.hasOwnProperty(key)){
                                obj["市县落实情况"][dic[key]] = vData.check[key];
                            }
                            if(vData.implement.hasOwnProperty(key)){
                                obj["省级行业主管部门核查情况"][dic[key]] = vData.implement[key];
                            }
                        }
                        store.commit("changeInfoBoxThreeContent", obj);
                        addBoundInfoBox(entity.position._value, "infoBox4");
                        currentEntity = entity
                    } else {
                        let vData = res.data.data;
                        let obj = {
                            "隐患基本情况":{},
                            "市县落实情况":{},
                            "省级行业主管部门核查情况":{}
                        };
                        let dic = doc[entity.type];
                        // 原顺序
                        for (let key in dic) {
                            if(vData.baseInfo.hasOwnProperty(key)){
                                obj["隐患基本情况"][dic[key]] = vData.baseInfo[key];
                            }
                            if(vData.check.hasOwnProperty(key)){
                                obj["市县落实情况"][dic[key]] = vData.check[key];
                            }
                            if(vData.implement.hasOwnProperty(key)){
                                obj["省级行业主管部门核查情况"][dic[key]] = vData.implement[key];
                            }
                        }
                        addBoundInfoBox(entity.position._value, "infoBox1");
                        store.commit("changeInfoBoxThreeContent", obj);
                    }
                });
            }
        };
        //弹出弹框 new Cesium.Cartesian2(offsetLeft + clientWidth, .offsetTop + clientHeight)
        const addBoundInfoBox = (positionValue, elementId) => {
            const oneDiv = window.document.getElementById(elementId);
            oneDiv.style.display = "block";
            let preRenderListener = viewer.scene.postRender.addEventListener(
                function () {
                    let elWidth = oneDiv.offsetWidth;
                    let elHeight = oneDiv.offsetHeight; // + 60
                    const scratch = new Cesium.Cartesian2(); //cesium二维笛卡尔 笛卡尔二维坐标系就是我们熟知的而二维坐标系；三维也如此
                    let position = positionValue;
                    var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position); //笛卡尔转84
                    var lat=Cesium.Math.toDegrees(cartographicPosition.latitude);
                    var lng=Cesium.Math.toDegrees(cartographicPosition.longitude);
                    var alt=cartographicPosition.height;
                    var positions = [
                            Cesium.Cartographic.fromDegrees(lng,lat)
                    ];
                    var carto=new Cesium.Cartographic.fromDegrees(lng,lat)　　//输入经纬度
                    var h2=viewer.scene.sampleHeight(carto);
                    // var promise = Cesium.sampleTerrainMostDetailed(window.dx, positions);//(地形数据，positions)
                    var position1 = Cesium.Cartesian3.fromDegrees(lng, lat,h2);//加入高度之后，不会飘，但是不能解决地球缩放问题
                    const canvasPosition =
                        viewer.scene.cartesianToCanvasCoordinates(
                            position1,
                            scratch
                        ); //cartesianToCanvasCoordinates 笛卡尔坐标（3维度）到画布坐标

                    if (Cesium.defined(canvasPosition)) {
                        // 根据元素宽高及当前点屏幕坐标进行偏移
                        oneDiv.style.top =
                            canvasPosition.y - elHeight * 1.1 + "px";
                        oneDiv.style.left =
                            canvasPosition.x - elWidth / 2 + "px";
                    }
                }
            );
        };
        const addAndRemove = (item) => {

            if(item.label=="渔船"){
                ElNotification({
                title: '渔船信息提示',
                message: h(
                    'i',
                    { style: 'color: teal' },
                    '渔船位置未提供，正在对接中，暂无法上球',
                ),
                });
            }else{ 
                if (item.state1) {
                    //添加点
                    let pointsDataUrl = `${sjzxUrl}${item.kbApiAll}`;
                    if (userRegion.value == "海南省") {
                    }else{
                        pointsDataUrl = `${sjzxUrl}${item.kbApiAll}?addvcd=${window.regionCode[userRegion.value]}`
                    }
                    axios.get(pointsDataUrl).then((res) => {
                        pointeManager.addPoints(
                            item.label,
                            res.data.data,
                            item.kbApiDetail,
                            "leftClick",
                            pointHandleClick
                        );
                    });
                } else {
                    //清除点
                    pointeManager.removePointBySign(item.label);
                    if(store.state.userRegion=="海南省"){
                        store.commit("changeSjzxLeftCurrentComponent", "SjzxBasic");
                    }else{
                        store.commit("changeSjzxLeftCurrentComponent", "");
                    }
                    
                }
            }
            
            
        };
        //右下面板点击每个类型
        const handleItemClick = (e, item, index) => {
            //每次加载点位，视角重新飞回海南视角
            // let hainanCamera = {
            //     destination: Cesium.Cartesian3.fromDegrees(
            //         109.75985598565222,
            //         19.261744640490033,
            //         471784
            //     ),
            // };
            // viewer.camera.flyTo(hainanCamera);

            let checkedCities = [];
            // 循环数组,实现选中和反选
            list.value.forEach((item1, index1) => {
                if (index1 == index) {
                    item1.state1 = !item1.state1;
                }
            });
            //选中后的最新的数组，更新给图例
            list.value.forEach((item1, index1) => {
                if (item1.state1) {
                    checkedCities.push(item1.label);
                }
            });
            //先去重
            checkedCities = Array.from(new Set(checkedCities));
          
            //没有被选项的时候，显示默认页面
            if (checkedCities.length == 0) {
                //全不选的时候
                if (userRegion.value == "海南省") {
                    store.commit("changeSjzxLeftCurrentComponent", "SjzxBasic");
                } else {
                    store.commit("changeSjzxLeftCurrentComponent", "");
                }
                
                store.commit("changeCheckedCities", checkedCities);
                pointeManager.removeAll();
            } else {
                //显示图例
                store.commit("changeFxffLegendShow", true);
                // 有被选中的时候，需要显示防汛防风面板，并设置最新的统计信息
                // 显示防风防汛左侧详情面板
                store.commit(
                    "changeSjzxLeftCurrentComponent",
                    "FxffThematicMapDetail"
                );
                // 与图例交互，已选数据传给图例，保持同步
                store.commit("changeCheckedCities", checkedCities);
                // 根据当前按钮选中状态，添加点位或者清除点位
                addAndRemove(item);
                // 点哪个按钮，就传给左侧面板什么数据，用来左侧面板显示数据，
                // 图表数据 和 列表数据
                switch (item.label) {
                    case "水库":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["水库市县统计", "水库工程规模统计"],
                            item,
                            type: "水库",
                        });
                        
                        break;
                    case "地质灾害隐患点":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: [
                                "市县统计",
                                "灾害类型统计",
                                "灾害规模统计",
                            ],
                            item,
                            type: "地质灾害隐患点",
                        });

                        break;
                    case "漫水桥(路)":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["市县统计"],
                            item,
                            type: "漫水桥(路)",
                        });

                        break;
                    case "危房":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["危房市县统计"],
                            item,
                            type: "危房",
                        });

                        break;
                    case "旅游景区景点":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["市县统计", "日最大承载游客量统计"],
                            item,
                            type: "旅游景区景点",
                        });

                        break;
                    case "易淹易涝点(区)":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: [
                                "市县统计",
                                "影响人数统计",
                                "影响户数统计",
                            ],
                            item,
                            type: "易淹易涝点(区)",
                        });

                        break;

                    case "渔船":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["渔船市县统计", "渔船抗风等级统计"],
                            item,
                            type: "渔船",
                        });

                        break;

                    case "渔港":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: [
                                "渔港市县统计",
                                "避风船只容量统计",
                                "抗风能力统计",
                            ],
                            item,
                            type: "渔港",
                        });
                        
                        break;
                    case "塔吊":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["塔吊市县统计"],
                            item,
                            type: "塔吊",
                        });

                        break;
                    case "其他":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["其他市县统计"],
                            item,
                            type: "其他",
                        });

                        break;
                    case "三防责任人信息":
                        store.commit("changeFxffThematicMapCheckedContent", {
                            echarts: ["市县统计"],
                            item, 
                            type: "三防责任人信息",
                        });

                        break;
                }
            }
        };
        onBeforeUnmount(() => {
            store.commit("changeFxffLegendShow", false);
            pointeManager.removeAll();
            removeInfoBox();
        });
        return {
            list,
            handleItemClick,
        };
    },
};
</script>

<style lang="stylus" scoped>
.rightThematicMapFxff {
    background: url('/images/sjzx/list.png') no-repeat;
    background-size: 100% 100%;
    width: vw(370);
    height: vh(555);
    margin-top: vh(15);
    .title {
        text-align: center;
        font-size: vw(16);
        margin-left: vw(10);
    }

    .thematicMap {
        width: 100%;
        display: grid;
        grid-template-columns: vw(180) vw(180);
        grid-row-gap: vh(30);
        grid-column-gap: vw(3);
        margin-top: vh(50);
        margin-left: vh(10);

        .thematicMapItem {
            display: flex;
            justify-content: space-around;
            background: url('/images/sjzx/item.png') no-repeat;
            background-size: 100% 100%;
            line-height: vh(37);
            height: vh(37);
            font-size: vw(14);
            margin-right: vw(20);
            cursor: pointer;
            .dataName{
                width:100%;
                display:flex;
                justify-content :flex-start;
                .dataImg{
                    img{
                        width: vw(27);
                        height: vh(27);
                        line-height:vh(37);
                        margin-top:vh(4);
                        margin-left: vw(10);
                        margin-right: vw(10);
                    }
                }
                .dataWord{
                    
                }
            }
        }

        .thematicMapItemActive {
            div {
                color: #00F4FD;
            }
        }
    }
}
</style>